package com.hc.appanimal;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;

import com.hc.DTO.AnimalDTO;
import com.hc.constants.Constants;
import com.hc.ultil.PicassoUtils;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.listener.ImageLoadingProgressListener;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class SummaryActivity extends Activity implements OnClickListener {
	WebView wvDetail;
	Button btnMap, btnGallery, btnHome, btnDetail;
	AnimalDTO animalDTO;
	TextView txtTitle;
	Button btnBack;
	TextView txtScientificName, txtWLPA, txtCITES;
	ImageView imgAnimal, imgWLPA;
	DisplayImageOptions options;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_summary);
		initImageLoader(getApplicationContext());
		options = new DisplayImageOptions.Builder()
				.showImageOnLoading(R.drawable.ic_stub)
				.showImageForEmptyUri(R.drawable.ic_empty)
				.showImageOnFail(R.drawable.ic_error).cacheInMemory(true)
				.cacheOnDisk(true).considerExifParams(true)
				.bitmapConfig(Bitmap.Config.RGB_565).build();

		txtScientificName = (TextView) findViewById(R.id.ScientificName);
		txtWLPA = (TextView) findViewById(R.id.txtWLPA);
		txtCITES = (TextView) findViewById(R.id.txtCITES);
		imgAnimal = (ImageView) findViewById(R.id.imgAnimal);
		imgWLPA = (ImageView) findViewById(R.id.imgWLPA);

		txtTitle = (TextView) findViewById(R.id.txtTitle);
		txtTitle.setTextSize(15.0f);
		btnBack = (Button) findViewById(R.id.btnBack);
		btnBack.setVisibility(View.VISIBLE);
		btnBack.setOnClickListener(this);
		Bundle data = getIntent().getExtras();
		if (data != null) {
			animalDTO = (AnimalDTO) data.getSerializable("images");
		}

		// AnimalModel model = AnimalModel.getInstance();
		// animalDTO = model.getAnimalById(this, dto.getId());
		wvDetail = (WebView) findViewById(R.id.wvDetail);

		btnMap = (Button) findViewById(R.id.btnMap);
		btnGallery = (Button) findViewById(R.id.btnGallery);
		btnMap.setOnClickListener(this);
		btnGallery.setOnClickListener(this);
		btnHome = (Button) findViewById(R.id.btnHome);
		btnHome.setOnClickListener(this);
		btnDetail = (Button) findViewById(R.id.btnDetail);
		btnDetail.setOnClickListener(this);
		String CommonName = animalDTO.getCommonName();
		if (CommonName.equalsIgnoreCase("null"))
			CommonName = "";
		String ScientificName = animalDTO.getScientificName();
		if (ScientificName.equalsIgnoreCase("null"))
			ScientificName = "";
		String RegionalName = animalDTO.getRegionalName();
		if (RegionalName.equalsIgnoreCase("null"))
			RegionalName = "";
		String WLPA = animalDTO.getwLPA();
		if (WLPA.equalsIgnoreCase("null"))
			WLPA = "";
		String getSmallNote = animalDTO.getSmallNote();
		if (getSmallNote.equalsIgnoreCase("null"))
			getSmallNote = "";
		String getMoreInfo = animalDTO.getMoreInfo();
		if (getMoreInfo.equalsIgnoreCase("null"))
			getMoreInfo = "";

		txtScientificName.setText(ScientificName);

		// ArrayList<String> strImg = new ArrayList<String>();
		String urlImg = "file:///android_asset/IUCN/";

		String IUCN = animalDTO.getiUCN();
		// if (!IUCN.equalsIgnoreCase("null")) {
		// IUCN = urlImg + IUCN + ".png";
		// } else {
		// IUCN = "";
		// }
		String CITES = animalDTO.getcITES();
		if (CITES.equalsIgnoreCase("null"))
			CITES = "";
		txtTitle.setText(animalDTO.getCommonName());
		txtWLPA.setText("WLPA - " + WLPA);
		txtCITES.setText("CITIES - " + CITES);
		int resID = getResources().getIdentifier(IUCN + ".png", "drawable",
				getPackageName());
		imgWLPA.setImageResource(resID);
		PutImage(imgWLPA, IUCN);

		// imgWLPA.setImageResource(R.drawable.);
		
		String path = animalDTO.getAnimalImagesDTO().getImageUrl();
		path = path.replaceAll(" ", "%20");
		if(path != null){
			String[] strs = path.split("/");
			File f = new File(Environment.getExternalStorageDirectory() + "/"
					+ Constants.APP_NAME + "/" + strs[4] + "/" + strs[5]);
			String pathImg = "file://" + f.getAbsolutePath();
			if(f.exists()){
				ImageLoader.getInstance().displayImage(
						pathImg, imgAnimal,
						options, new SimpleImageLoadingListener() {
							@Override
							public void onLoadingStarted(String imageUri, View view) {

							}

							@Override
							public void onLoadingFailed(String imageUri, View view,
									FailReason failReason) {

							}

							@Override
							public void onLoadingComplete(String imageUri, View view,
									Bitmap loadedImage) {

							}
						}, new ImageLoadingProgressListener() {
							@Override
							public void onProgressUpdate(String imageUri, View view,
									int current, int total) {

							}
						});
			}else {
				PicassoUtils.getInstance().showImageFromUrl(SummaryActivity.this, path,
						R.drawable.spin_animation, imgAnimal);
				// TODO: create folder?

				PicassoUtils.getInstance().saveImageFromUrl(
						this.getApplicationContext(), path, strs[5],
						strs[4]);
			}
			
		}
		

		// wvAbout.setBackgroundColor(0);
		// wvAbout.setBackgroundResource(Color.TRANSPARENT);
		// wvAbout.loadData(str, "text/html", "utf8");
		String t = "This medium-sized sheep is 115 to 165&nbsp;cm (45 to 65&nbsp;in) long along the head-and-body, with a tail of 10 to 20&nbsp;cm (3.9 to 7.9&nbsp;in). They stand 69 to 91&nbsp;cm (27 to 36&nbsp;in) high at the shoulder. Body mass can range from 35 to 75&nbsp;kg (77 to 165&nbsp;lb). Males are slightly larger than females. The short, dense coat is slate grey in colour, sometimes with a bluish sheen. The underparts and backs of the legs are white, while the chest and fronts of the legs are black. Separating the grey back and white belly is a charcoal colored stripe. The ears are small, and the bridge of the nose is dark. The horns are found in both sexes, and are ridged on the upper surface. In males, they grow upwards, then turn sideways and curve backwards, looking somewhat like an upside-down moustache. They may grow to a length of 80&nbsp;cm (31&nbsp;in). In females, the horns are much shorter and straighter, growing up to 20&nbsp;cm (7.9&nbsp;in) long";
		wvDetail.loadDataWithBaseURL(null,
				"<html><body background=\"#00000000\" link=\"white\"><font color=\"black\">"
						+ "<p text-align=\"right\">" + "<b>"
						+ "Regional name: " + "</b>" + RegionalName + "<br>"+ "<br>"
						+ "<b>" + "General description :" + "</b>"
						+ getSmallNote //+ getMoreInfo

						+ "</p>" + "</font></body</html>", "text/html",
				"UTF-8", null);
		wvDetail.setBackgroundColor(0x00000000);
		if (Build.VERSION.SDK_INT >= 11) // Android v3.0+
			try {
				Method method = View.class.getMethod("setLayerType", int.class,
						Paint.class);
				method.invoke(wvDetail, 1, new Paint()); // 1 =
															// LAYER_TYPE_SOFTWARE
															// (API11)
			} catch (Exception e) {
			}

		btnMap.setBackgroundResource(R.drawable.animal_map);
		btnGallery.setBackgroundResource(R.drawable.animal_images);
		btnDetail.setBackgroundResource(R.drawable.animal_details);
		btnHome.setBackgroundResource(R.drawable.animal_homef);
	}

	public void PutImage(ImageView v, String filename) {
		try {
			v.setImageDrawable(Drawable.createFromStream(
					getAssets().open("IUCN/" + filename + ".png"), null));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static void initImageLoader(Context context) {
		// This configuration tuning is custom. You can tune every option, you
		// may tune some of them,
		// or you can create default configuration by
		// ImageLoaderConfiguration.createDefault(this);
		// method.
		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
				context).threadPriority(Thread.NORM_PRIORITY - 2)
				.denyCacheImageMultipleSizesInMemory()
				.diskCacheFileNameGenerator(new Md5FileNameGenerator())
				.diskCacheSize(50 * 1024 * 1024)
				// 50 Mb
				.tasksProcessingOrder(QueueProcessingType.LIFO)
				.writeDebugLogs() // Remove for release app
				.build();
		// Initialize ImageLoader with configuration.
		ImageLoader.getInstance().init(config);
	}

	@Override
	public void onClick(View v) {
		Intent intent;
		Bundle data = null;
		switch (v.getId()) {

		case R.id.btnMap:
			intent = new Intent(SummaryActivity.this, MapActivity.class);
			data = new Bundle();
			data.putSerializable("images", animalDTO);
			intent.putExtras(data);
			startActivity(intent);
			finish();
			break;
		case R.id.btnGallery:
			intent = new Intent(SummaryActivity.this, GalleryActivity.class);
			data = new Bundle();
			data.putSerializable("images", animalDTO);
			intent.putExtras(data);
			startActivity(intent);
			finish();
			break;
		case R.id.btnBack:
			finish();
			break;
		case R.id.btnDetail:
			intent = new Intent(SummaryActivity.this,
					DetailAnimalActivity.class);
			data = new Bundle();
			data.putSerializable("images", animalDTO);
			intent.putExtras(data);
			startActivity(intent);
			finish();
			break;

		default:
			break;
		}

	}
}
